package com.qiall.omsserver.service.dubbo;


import com.qiall.common.request.BaseResponse;
import com.qiall.oms.ability.ReportDubboService;
import com.qiall.oms.ability.request.ReportDubboRequest;
import com.qiall.omsserver.data.entity.DubboServiceInfo;
import com.qiall.omsserver.data.mapper.DubboServiceInfoMappr;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@DubboService
public class ReportDubboServiceImpl implements ReportDubboService {
    @Autowired
    private DubboServiceInfoMappr dubboServiceInfoMappr;

    @Override
    public BaseResponse reportDubboService(ReportDubboRequest request) {
        List<DubboServiceInfo> dubboServiceInfos = new ArrayList<>();
        if(request.getServiceList()==null){
            return new BaseResponse();
        }
        for (ReportDubboRequest.ServiceInfo serviceInfo : request.getServiceList()) {
            dubboServiceInfos.add(buildDubboServiceInfo(request, serviceInfo));
        }
        dubboServiceInfoMappr.deleteByApplicationNameAndIp(request.getIp(), request.getApplicationName());
        for (DubboServiceInfo dubboServiceInfo : dubboServiceInfos) {
            dubboServiceInfoMappr.insert(dubboServiceInfo);
        }
        BaseResponse baseResponse = new BaseResponse();
        return baseResponse;
    }

    public DubboServiceInfo buildDubboServiceInfo(ReportDubboRequest request, ReportDubboRequest.ServiceInfo serviceInfo) {
        DubboServiceInfo dubboServiceInfo = new DubboServiceInfo();

        String ip = request.getIp();
        Integer port = request.getPort();
        String serviceGroup = request.getDefaultGroup();
        String applicationName = request.getApplicationName();
        dubboServiceInfo.setApplicationName(applicationName);
        dubboServiceInfo.setVersion(serviceInfo.getVersion());
        dubboServiceInfo.setIp(ip);
        dubboServiceInfo.setPort(port);
        dubboServiceInfo.setServiceName(serviceInfo.getService());
        if (StringUtils.isNotBlank(serviceInfo.getGroup())) {
            dubboServiceInfo.setServiceGroup(serviceInfo.getGroup());
        } else {
            dubboServiceInfo.setServiceGroup(serviceGroup);
        }
        dubboServiceInfo.setMethods(serviceInfo.getMethodsJson());
        return dubboServiceInfo;

    }

}
